package com.thug.engine;

import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.ZoomCamera;

public class ZoomCameraController {
	
	private final static float ZOOM_MAX_VALUE = 2.0f;
	private final static float ZOOM_MIN_VALUE = 1.0f;

	private ZoomCamera mCamera;
	private BaseGameEntity mControllingEntity;
	private float mZoomMax;
	private float mZoomMin;
	private float mPrevX;
	private float mPrevY;
	private float mZoomResolution;
	private float mZoomMinClip;
	private float mZoomMaxClip;
	private float mPrevSpeed;


	public ZoomCameraController(Camera camera, BaseGameEntity entity) {
		mCamera = (ZoomCamera) camera;
		mControllingEntity = entity;
		mZoomMax = ZOOM_MAX_VALUE;
		mZoomMin = ZOOM_MIN_VALUE;
		mPrevX = 0.0f;
		mPrevY = 0.0f;
		mZoomMinClip = 1;
		mZoomMaxClip = 3;
		mZoomResolution = 0.2f;
		mCamera.setZoomFactor(2);
	}

	public void setBounds(float boundMinX, float boundMaxX, float boundMinY, float boundMaxY) {
		mCamera.setBounds(boundMinX, boundMaxX, boundMinY, boundMaxY);
	}
	
	public void setBoundsEnabled(boolean boundsEnabled) {
		mCamera.setBoundsEnabled(boundsEnabled);
	}

	public void update(float elapsedTime) {
		float entPosX = mControllingEntity.getX();
		float entPosY = mControllingEntity.getY();
		float camPosX = mCamera.getCenterX();
		float camPosY = mCamera.getCenterY();
		float posX = camPosX;
		float posY = camPosY;

		if(entPosX > camPosX + 160) {
			posX = entPosX - 160;
		}
		else if(entPosX < camPosX - 160) {
			posX = entPosX + 160;
		}

		if(entPosY > camPosY + 106) {
			posY = entPosY - 106;
		}
		else if(entPosY < camPosY - 106) {
			posY = entPosY + 106;
		}

		//mC.set
		mCamera.setCenter(posX, posY);

		/*
		// auto zooming on speed 
		float speedzoom = 1;
		float x_d = mPrevX - entPosX;
		float y_d = mPrevY - entPosY;
		float speed = (float) Math.sqrt(x_d * x_d + y_d * y_d);

		float totalZoom =  mCamera.getZoomFactor();
		if(speed > 5) {
			if(speed > mPrevSpeed) {
				totalZoom = totalZoom + (speed - mPrevSpeed);
			}
		}
		if(speed < mPrevSpeed) {
			totalZoom = totalZoom - (mPrevSpeed - speed);
		}


		mPrevX = entPosX;
		mPrevY = entPosY;
		mPrevSpeed =speedzoom;

		// perform clipping
		if(totalZoom > mZoomMaxClip) {
			totalZoom = mZoomMaxClip;
		}
		else if(totalZoom < mZoomMinClip){
			totalZoom = mZoomMinClip;
		}

		mCamera.setZoomFactor(totalZoom);*/
	}

	public void btnZoomIn() {
		float zoomInfactor = mCamera.getZoomFactor() + mZoomResolution;
		if(zoomInfactor > mZoomMax) {
			zoomInfactor = mZoomMax;
		}
		mCamera.setZoomFactor(zoomInfactor);
	}

	public void btnZoomOut() {
		float zoomOutfactor = mCamera.getZoomFactor() - mZoomResolution;
		if(zoomOutfactor < mZoomMin) {
			zoomOutfactor = mZoomMin;
		}
		mCamera.setZoomFactor(zoomOutfactor);
	}

}
